package com.yilian.xlmusic.android.view.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.minlukj.mediaplaylib.MediaPlayInfoListener;
import com.yilian.xlmusic.android.R;
import com.yilian.xlmusic.android.XlMusicActivity;
import com.yilian.xlmusic.android.base.MyApplication;
import com.yilian.xlmusic.android.utils.DeviceIdUtils;
import com.yilian.xlmusic.android.utils.MeasureUnitTranUtil;
import com.yilian.xlmusic.android.utils.SelectCallBack;
import com.yilian.xlmusic.android.utils.SuperCustomToast;
import com.yilian.xlmusic.android.utils.Utils;
import com.yilian.xlmusic.android.utils.ViewAnimator;
import com.yilian.xlmusic.android.utils.net.AppConstants;
import com.yilian.xlmusic.android.utils.port.ClickListener;
import com.yilian.xlmusic.android.utils.view.CollectCheckBox;
import com.yilian.xlmusic.android.view.bean.ChangeItem;
import com.yilian.xlmusic.android.view.bean.CollectionBean;
import com.yilian.xlmusic.android.view.bean.MusicPlayerBean;
import com.yilian.xlmusic.android.view.bean.ReturnResult;
import com.yilian.xlmusic.android.view.bean.UrlBean;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import rxhttp.RxHttp;

public class ItemRecycleViewAdapter extends BaseQuickAdapter<MusicPlayerBean.DataBean, BaseViewHolder> {
    private boolean is_last_page;
    private int width, dip2px;
    private SelectCallBack selectCallBack;
    private long timeClock = 0;

    public ItemRecycleViewAdapter(int layoutResId, @Nullable List<MusicPlayerBean.DataBean> data, boolean m_is_last_page) {
        super(layoutResId, data);
        is_last_page = m_is_last_page;
        selectCallBack = AppConstants.selectCallBack;
        WindowManager wm = (WindowManager) MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels - MeasureUnitTranUtil.dip2px(MyApplication.getContext(), 20);// 屏幕宽度（像素）
        if (is_last_page) {
            dip2px = MeasureUnitTranUtil.dip2px(MyApplication.getContext(), 90);
        } else {
            dip2px = MeasureUnitTranUtil.dip2px(MyApplication.getContext(), 70);
        }
    }


    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, MusicPlayerBean.DataBean data, @NotNull List<?> payloads) {
        LinearLayout root_view = baseViewHolder.itemView.findViewById(R.id.root_view);
        LinearLayout right_item_layout = baseViewHolder.itemView.findViewById(R.id.right_item_layout);
        ImageView play_icon = baseViewHolder.itemView.findViewById(R.id.play_icon);
        for (Object p : payloads) {
            MusicPlayerBean.DataBean NewData = (MusicPlayerBean.DataBean) p;

            if (NewData.isIs_play()) {
                play_icon.setImageResource(R.drawable.playing_icon);
//                    if(is_last_page){
//                        setLastPageMargin(0, root_view, right_item_layout);
//                    }
                ViewAnimator.doAnim(baseViewHolder.itemView.findViewById(R.id.music_constraint), "width", width, width - dip2px);
            } else {
//                    if(is_last_page){
//                        setLastPageMargin(40, root_view, right_item_layout);
//                    }
                play_icon.setImageResource(R.drawable.play_icon);
                ViewAnimator.doAnim(baseViewHolder.itemView.findViewById(R.id.music_constraint), "width", width - dip2px, width);

            }

        }


    }


    private void getMusicUrl(ChangeItem changeItem) {
        AppConstants.METHOD_NAME = "获取音乐地址：";
        Disposable subscribe = RxHttp.get("/ylmusic-gateway/play")
                .addHeader(AppConstants.ACCESS_TOKEN_KEY, AppConstants.ACCESS_TOKEN)
                .add("identity", DeviceIdUtils.getDeviceId(MyApplication.getContext()))
                .add("id", changeItem.getDataBean().getId())
                .asClass(UrlBean.class)
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.newThread())
                .subscribe(result -> {
                    changeItem.getDataBean().setNet_play_url(result.getPlay_url());
                    PlayMusicMethod(new ChangeItem(changeItem.getChangeData(), changeItem.getDataBean(), changeItem.getItemRecycleViewAdapter(), changeItem.getChangePosition()));
                }, throwable -> {
                    SuperCustomToast.getInstance(getContext()).show("服务器异常~");
                });
    }

    private void playMusic(ChangeItem item) {
        XlMusicActivity.mMediaPlayerUtils.stop();
        XlMusicActivity.mMediaPlayerUtils.setNetPath(item.getDataBean().getNet_play_url());
        boolean start = XlMusicActivity.mMediaPlayerUtils.start();
        if (start) {
            item.getDataBean().setIs_play(true);
        } else {
            item.getDataBean().setIs_play(false);
        }

    }


    private void stopMusic(ChangeItem item) {
        XlMusicActivity.mMediaPlayerUtils.stop();
        item.getDataBean().setIs_play(false);
    }

    private void PlayMusicMethod(ChangeItem changeItem) {
        //添加缓存ID
        if (AppConstants.changeItems.size() > 0) {//说明有正在播放的音乐
            MusicPlayerBean.DataBean playDate = AppConstants.changeItems.get(0).getDataBean();
            if (XlMusicActivity.mMediaPlayerUtils.isPlaying()) {
                if (playDate.getId() != changeItem.getDataBean().getId()) {//表示切换了歌曲
                    playMusic(changeItem);
                } else {//表示点击的同一个歌曲,第二次点击暂停
                    stopMusic(changeItem);
                }
            } else {
                playMusic(changeItem);
            }
        } else {
            playMusic(changeItem);
        }
        XlMusicActivity.mMediaPlayerUtils.setMediaPlayInfoListener(new MediaPlayInfoListener() {
            @Override
            public void onError(MediaPlayer mp, int what, int extra) {

            }

            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                changeItem.getDataBean().setIs_play(true);
                refreshView(changeItem, true);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {

            }

            @Override
            public void onSeekComplete(MediaPlayer mediaPlayer) {
            }

            @Override
            public void onSeekBarProgress(int progress) {

            }
        });


    }


    private void updateUi(ChangeItem changeItem) {
        if (AppConstants.changeItems.size() > 0) {
            ItemRecycleViewAdapter oldAdapter = AppConstants.changeItems.get(0).getItemRecycleViewAdapter();
            int oldPosition = AppConstants.changeItems.get(0).getChangePosition();
            MusicPlayerBean.DataBean olddata = AppConstants.changeItems.get(0).getDataBean();
            if (!(oldPosition == changeItem.getChangePosition() && oldAdapter == changeItem.getItemRecycleViewAdapter())) {//非当前条目刷新
                if (olddata.isIs_play()) {//旧的如果还在播放就刷新旧的
                    refreshView(AppConstants.changeItems.get(0), false);
                }
            }
            refreshView(changeItem, false);
            AppConstants.changeItems.clear();
            AppConstants.changeItems.add(new ChangeItem(getData(), changeItem.getDataBean(), changeItem.getItemRecycleViewAdapter(), changeItem.getChangePosition()));
        } else {//第一次点击时

            AppConstants.changeItems.add(new ChangeItem(getData(), changeItem.getDataBean(), changeItem.getItemRecycleViewAdapter(), changeItem.getChangePosition()));
            refreshView(changeItem, false);
        }
    }

    private void refreshView(ChangeItem refresh_item, boolean isCompelete) {
        refresh_item.getDataBean().setIs_play(!refresh_item.getDataBean().isIs_play());
        refresh_item.setDataBean(refresh_item.getDataBean());
        refresh_item.getItemRecycleViewAdapter().getData().set(refresh_item.getChangePosition(), refresh_item.getDataBean());
        refresh_item.getItemRecycleViewAdapter().notifyItemChanged(refresh_item.getChangePosition(), refresh_item.getDataBean());
        //播放音乐
        if (!isCompelete) {
            if (refresh_item.getDataBean().getNet_play_url() != null) {
                Log.e("音乐URIL", refresh_item.getDataBean().getNet_play_url());
                PlayMusicMethod(refresh_item);
            } else {
                getMusicUrl(refresh_item);
            }
        }


    }

    private void setLastPageMargin(int margin_size, LinearLayout rootView, LinearLayout right_item_layout) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) right_item_layout.getLayoutParams();
        layoutParams.setMargins(0, 0, MeasureUnitTranUtil.dip2px(MyApplication.getContext(), margin_size), 0);
        rootView.setLayoutParams(layoutParams);
    }


    @Override
    protected void convert(@NotNull BaseViewHolder baseViewHolder, MusicPlayerBean.DataBean data) {
        ConstraintLayout music_constraint = baseViewHolder.itemView.findViewById(R.id.music_constraint);
        TextView music_employ = baseViewHolder.itemView.findViewById(R.id.music_employ);
        CollectCheckBox checkBox = baseViewHolder.itemView.findViewById(R.id.music_collect);
        baseViewHolder.setText(R.id.music_title, data.getName());
        baseViewHolder.setText(R.id.music_title, data.getName());
        baseViewHolder.setText(R.id.music_author, data.getArtist());
        baseViewHolder.setText(R.id.music_time, data.getDuration());
        ImageView play_icon = baseViewHolder.itemView.findViewById(R.id.play_icon);
        ViewGroup.LayoutParams params = music_constraint.getLayoutParams();
        if (data.isIs_play()) {
            play_icon.setImageResource(R.drawable.playing_icon);
            params.width = width - dip2px;
        } else {
            play_icon.setImageResource(R.drawable.play_icon);
            params.width = width;
        }
        music_constraint.setLayoutParams(params);
        //最后一页需要调整右间距
//        if(is_last_page){
//            setLastPageMargin(20, right_item_layout, music_employ);
//        }
        ImageView icon = baseViewHolder.getView(R.id.music_bg);
        Utils.loadRoundImage(data.getCover(), icon, 20);
        checkBox.defaultChecked(data.isCollected());
        //收藏
        checkBox.bindListener(new ClickListener() {
            @Override
            public void click() {
                if (timeClock == 0) {
                    AppConstants.METHOD_NAME = "收藏：";
                    RxHttp.postForm("/ylmusic-gateway/collect")
                            .addHeader(AppConstants.ACCESS_TOKEN_KEY, AppConstants.ACCESS_TOKEN)
                            .add("music_id", data.getId())
                            .asClass(CollectionBean.class)
                            .observeOn(AndroidSchedulers.mainThread())  //主线程回调观察者
                            .subscribe(result -> {
                                data.setCollected(result.getData().isCollected());
                                checkBox.setCheckBox(result.getData().isCollected());
                            }, throwable -> {
                                SuperCustomToast.getInstance(getContext()).show("收藏失败~");
                            });
                    setTimeClock();
                }
            }
        });

        //使用
        music_employ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.getNet_play_url() != null) {
                    ReturnResult(data, data.getNet_play_url());
                } else {
                    //请求网络获取地址
                    AppConstants.METHOD_NAME = "获取音乐地址：";
                    RxHttp.get("/ylmusic-gateway/play")
                            .addHeader(AppConstants.ACCESS_TOKEN_KEY, AppConstants.ACCESS_TOKEN)
                            .add("identity", DeviceIdUtils.getDeviceId(MyApplication.getContext()))
                            .add("id", data.getId())
                            .asClass(UrlBean.class)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(Schedulers.newThread())
                            .subscribe(result -> {
                                data.setNet_play_url(result.getPlay_url());
                                ReturnResult(data, data.getNet_play_url());
                            }, throwable -> {
                                SuperCustomToast.getInstance(getContext()).show("服务器异常~");
                            });
                }

            }
        });

        music_constraint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //播放音乐
                if (timeClock == 0) {
                    updateUi(new ChangeItem(getData(), data, ItemRecycleViewAdapter.this, baseViewHolder.getAdapterPosition()));
                    setTimeClock();
                }

            }
        });
    }

    private void ReturnResult(MusicPlayerBean.DataBean data, String play_url) {
        ReturnResult returnResult = new ReturnResult();
        returnResult.setId(data.getId());
        returnResult.setArtist(data.getArtist());
        returnResult.setCover(data.getCover());
        returnResult.setDuration(data.getDuration());
        returnResult.setName(data.getName());
        returnResult.setPlay_url(play_url);
        selectCallBack.return_result(returnResult);
        //关闭activity
        MyApplication.destoryActivity(XlMusicActivity.TAG);
    }

    /**
     * 时间锁
     */
    private void setTimeClock() {
        long time;
        if (timeClock == 0) {
            time = 200;
        } else {
            time = timeClock;
        }
        new CountDownTimer(time, 100) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                timeClock = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                timeClock = 0;
            }
        }.start();
    }
}
